package com.keepers.repair.activity

import android.Manifest
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.v7.widget.AppCompatButton
import com.keepers.repair.R
import com.keepers.repair.helper.IntentHelper
import com.keepers.repair.helper.SpHelper
import com.keepers.repair.net.DataLoader
import com.keepers.repair.utils.AlertToast
import com.keepers.repair.utils.CollectionUtil
import com.werb.permissionschecker.PermissionChecker
import org.jetbrains.anko.find
import org.jetbrains.anko.indeterminateProgressDialog

class LoginActivity : BaseActivity() {

    private val PERMISSIONS = arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)

    private lateinit var usernameInput: TextInputEditText
    private lateinit var passwordInput: TextInputEditText
    private lateinit var button: AppCompatButton
    private lateinit var setting: AppCompatButton
    private lateinit var permissionChecker: PermissionChecker


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        transparencyBar()
        setContentView(R.layout.activity_login)
        permissionChecker = PermissionChecker(this)
        val loginUserInfo = SpHelper.getLoginUserInfo()
        if (loginUserInfo.UserName != null) {
            login(loginUserInfo.UserName, loginUserInfo.password)
            return
        }
        usernameInput = find(R.id.login_text_input_edit_text_username)
        passwordInput = find(R.id.login_text_input_edit_text_password)
        button = find(R.id.login_button)
        setting = find(R.id.setting_button)
        button.setOnClickListener { _ ->
            if (usernameInput.text.isNullOrEmpty()) {
                AlertToast.show("用户名不能为空")
                return@setOnClickListener
            }
            if (passwordInput.text.isNullOrEmpty()) {
                AlertToast.show("密码不能为空")
                return@setOnClickListener
            }
            login(usernameInput.text.toString(), passwordInput.text.toString())
        }
        setting.setOnClickListener {
            IntentHelper.goNetSetting(this@LoginActivity)
        }
    }

    private fun login(userName: String, password: String) {
        val prgDialog = indeterminateProgressDialog("正在登录...")
        prgDialog.setCancelable(false)
        prgDialog.show()
        rxHelper.pend(DataLoader.login(userName, password) {
            prgDialog.dismiss()
            if (it == null || CollectionUtil.isEmpty(it.Users)) {
                AlertToast.show("登录失败")
                return@login
            }
            val user = it.Users[0]
            if (user.RoleName != "检修员" && user.RoleName != "管理员" && user.RoleName != "巡逻员") {
                AlertToast.show("您没有权限登录，请联系管理员确认")
                return@login
            }
            if(!user.isValidityDate){
                AlertToast.show("该账户过有效期时间")
                return@login
            }
            user.password = password
            SpHelper.setLoginUserInfo(user)
            checkPermission()
        })
    }

    private fun checkPermission() {
        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
            permissionChecker.requestPermissions()
        } else {
            IntentHelper.goMain(this@LoginActivity)
            this@LoginActivity.finish()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == PermissionChecker.PERMISSION_REQUEST_CODE && permissionChecker.hasAllPermissionsGranted(grantResults)) {
            IntentHelper.goMain(this@LoginActivity)
        } else {
            AlertToast.show("请开启权限！")
        }
        this@LoginActivity.finish()
    }
}
